package ipcards.net;
import ipcards.Controller;
import ipcards.Room;
import ipcards.Table;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.*;


/**
* The main server for IPCards. Listens for connections from clients.
* Contains the {@link Room} which contains the {@link Table} objects.
* 
* @author Ricky Vincent
*/
public class CardsServer implements Runnable {
	
	private int port = Controller.DEFAULT_PORT;
	private ServerSocket server;
	public static Vector<Client> clients;
	private Controller controller;
	
	private boolean serverRunning = true;
	
	/**
	 * Constructs a new server to listen for connections from clients on the specified port.
	 * @param port The port to listen for incoming connections.
	 * @throws IOException 
	 */
	public CardsServer (int port, Controller controller) throws IOException {
		this.controller = controller;
		this.port = port;
		server = new ServerSocket(port);
		clients = new Vector<Client>();
	}
	
	/**
	 * Constructs a new server to listen for connections from clients.
	 * Listens on the default port.
	 * @throws IOException 
	 */
	public CardsServer (Controller controller) throws IOException {
		this.controller = controller;
		server = new ServerSocket(port);
		(this.controller).setCardsServer(this);
	}
	
	/**
	 * Listens for incoming connections. Creates a new {@link Client} object for each new connection.
	 */
	private void listen() {
		Client newClient;
		
		//infinite loop
		while (serverRunning) {
			
			try {
				newClient = new Client(server.accept(), controller.getRoom().getTable());
				Thread thread = new Thread(newClient);
				thread.start();
				clients.add(newClient);
				controller.serverPlayer(clients.size());
				//////
				
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
	}

	/**
	 * Implemented from <code>Runnable</code> interface. Called when thread starts.
	 */
	public void run() {
		listen();
	}
	
	/**
	 * Stops this server.
	 */
	public void stopServer() {
		try {
			server.close();
			serverRunning = false;
		} catch (IOException e) {
			//Already stopped?
			serverRunning = false;
		}
	}

	/**
	 * @return the model
	 */
	public Controller getModel() {
		return controller;
	}
	
	public int numPlayers() {
		return clients.size();
	}
}



